package com.vpclub.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author : leimingchao
 * @date Date : 2021年08月01日 21:37
 */
@Controller
public class FileUploadController {


    /**
     *      produces ="text/html;charset=utf-8" : 相当于给响应头添加了Content-Type能解决乱码
     *
     * 测试多文件上传
     * @param model
     * @param username
     * @param files
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST,produces ="text/html;charset=utf-8")
    public String upload(Model model,
                         @RequestParam(value = "username",required = false) String username,
                         @RequestParam(value = "headerImg") MultipartFile[] files) {

        for (MultipartFile multipartFile : files) {
            if (!multipartFile.isEmpty()) {
                //文件保存
                try {
                    multipartFile.transferTo(new File("D:\\upload\\" + multipartFile.getOriginalFilename()));
                    model.addAttribute("msg","文件上传成功了");
                } catch (Exception e) {
                    model.addAttribute("msg","文件上传失败了！" + e.getMessage());
                }
            }
        }

        return "forward:/index.jsp";
    }

    /**
     *
     * produces ="text/html;charset=utf-8" : 相当于给响应头添加了Content-Type能解决乱码
     * 测试单文件上传
     * @param model
     * @param username
     * @param file
     * @return
     */
    // @RequestMapping(value = "/upload", method = RequestMethod.POST,produces ="text/html;charset=utf-8")
    // public String upload(Model model,
    //                      @RequestParam(value = "username",required = false) String username,
    //                      @RequestParam(value = "headerImg") MultipartFile file) {
    //
    //     System.out.println("上传的文件信息");
    //     System.out.println("文件项的name：" + file.getName());
    //     System.out.println("文件的名字：" + file.getOriginalFilename());
    //
    //     //文件保存
    //     try {
    //         file.transferTo(new File("D:\\upload\\" + file.getOriginalFilename()));
    //         model.addAttribute("msg","文件上传成功了");
    //     } catch (Exception e) {
    //         model.addAttribute("msg","文件上传失败了！" + e.getMessage());
    //     }
    //
    //     return "forward:/index.jsp";
    // }
}
